package smartcarpool.smartspaceservice;

import android.app.PendingIntent;
import android.util.Log;
import sofia_kp.KPICore;

import java.util.Vector;


public class SmartSpaceUpdate implements Runnable {

	private KPICore smartSpace;
	private String HOST;
	private int PORT;
	private String SPACE_NAME;
	private Vector<Vector<String>> newTripleVector;
    private Vector<Vector<String>> oldTripleVector;
    private PendingIntent pendingIntent;

	public SmartSpaceUpdate(String HOST, int PORT, String SPACE_NAME, Vector<Vector<String>> newTripleVector, Vector<Vector<String>> oldTripleVector, PendingIntent pendingIntent) {
		this.HOST = HOST;
		this.PORT = PORT;
		this.SPACE_NAME = SPACE_NAME;
		this.newTripleVector = newTripleVector;
        this.oldTripleVector = oldTripleVector;
        this.pendingIntent = pendingIntent;
	}

	@Override
	public void run() {
        try {
            smartSpace = new KPICore(this.HOST, this.PORT, this.SPACE_NAME);
            String joinResult = smartSpace.join();
            if (smartSpace.xmlTools.isJoinConfirmed(joinResult)) {
                String updateResult = smartSpace.update(newTripleVector,oldTripleVector);
                if (smartSpace.xmlTools.isUpdateConfirmed(updateResult)) {
                    pendingIntent.send(SmartSpaceService.RESULT_SUCCESS_UPDATE);
                    Log.d("SmartSpaceUpdate "," Information has been updated");
                } else {
                    pendingIntent.send(SmartSpaceService.RESULT_FAILURE_UPDATE);
                    Log.d("SmartSpaceUpdate "," Error, while updating the information.");
                }
            } else {
                pendingIntent.send(SmartSpaceService.RESULT_FAILURE_JOIN);
            }

            smartSpace.leave();
        } catch (PendingIntent.CanceledException e){
            Log.e("SmartSpaceUpdate. Pending Intent Error, Canceled", e.toString());
            e.printStackTrace();
        } catch (Exception e) {
            Log.e("SmartSpaceUpdate Error", e.toString() + "\n Triple to update from " + oldTripleVector.toString() + "\n to "+ newTripleVector.toString());
            e.printStackTrace();
        }
	}
}
